#!/bin/bash

handle_failure() {
    echo "$1"
    exit 1
}

# React linting and formatting
# echo "Linting and formatting React..."
# if cd apps/ui; then
#     if ! yarn lint-staged; then
#         handle_failure "React linting failed. Aborting commit."
#     fi
# else
#     handle_failure "Failed to change directory to apps/ui. Aborting commit."
# fi

# # Go back to root directory
# cd ../..

# FastAPI formatting with black and linting with ruff
root_dir=$(git rev-parse --show-toplevel)

if cd "$root_dir/apps/server"; then
    staged_files=$(git diff --cached --name-only --diff-filter=ACM)
    if [ $? -ne 0 ]; then
        handle_failure "Failed to get staged files. Aborting commit."
    fi
    python_files=""

    # Accumulate staged python files
    for file in $staged_files; do
        if [[ $file == *.py ]]; then
            # Adjust the file path relative to the root directory
            python_files="$python_files $root_dir/$file"
        fi
    done

    # If there are no python files, skip the formatting and linting step
    if [ -z "$python_files" ]; then
        echo "No Python files staged. Skipping formatting and linting."
        exit 0
    fi

    echo "Checking Python files..."

    # Format with black
    if ! poetry run black $python_files; then
        handle_failure "Black formatting failed. Aborting commit."
    fi

    # Sort with isort
    if ! poetry run isort $python_files; then
        handle_failure "Isort failed to sort Python imports. Aborting commit."
    fi

    # Stage the formatted files
    if ! git add $python_files; then
        handle_failure "Failed to stage Python files. Aborting commit."
    fi

    # Return to the root directory
    cd ../..

    echo "Pre-commit checks passed!"
else
    handle_failure "Failed to change directory to apps/server. Aborting commit."
fi
